//
//  packet.c
//  reli_udp
//
//  Created by Eric Sun on 11/20/12.
//  Copyright (c) 2012 Eric Sun. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <stdint.h>
#include "packet.h"
#include "para.h"

// reset select's fd_set and tv
void reset_select(int * sockfd, fd_set * fds, struct timeval * tv) {
    FD_ZERO(fds);
    FD_SET(*sockfd, fds);
    tv->tv_sec = TIMEOUT;
    tv->tv_usec = 0.0;
}

void makeFin(struct Packet * packet) {
    bzero(packet, PACKET_SIZE);
    packet->flagFin = 1;
}

void makeReq(struct Packet * packet, char * filename) {
    bzero(packet, PACKET_SIZE);
    packet->flagReq = 1;
    strncpy(packet->data, filename, strlen(filename));
}

void makeAck(struct Packet * packet, unsigned int ack_num) {
    bzero(packet, PACKET_SIZE);
    packet->flagAck = 1;
    packet->ack = ack_num;
}

void makeSeq(struct Packet * packet, unsigned int seq_num, char * buffer, size_t len) {
    bzero(packet, PACKET_SIZE);
    packet->seq = seq_num;
    packet->len = len;
    memcpy(packet->data, buffer, len);
}

void sendPacket(int sockfd, struct sockaddr * addr, struct Packet * packet) {
    char send_buffer[BUFFER_SIZE];
    memcpy(send_buffer, (char *)packet, BUFFER_SIZE);
    if (sendto(sockfd, send_buffer, BUFFER_SIZE, 0,
       addr, sizeof(*addr)) == -1) {
        perror("send error");
        exit(1);
    }
    else if (packet->flagReq) {
        printf("Request sent.\n");
    }
}